<template>
  <el-dialog
    title="设备退库"
    :close-on-click-modal="false"
    :visible.sync="dialogTablesVisible"
    :modal-append-to-body="false"
    id="equipments"
  >
    <template>
      <el-tabs v-model="activeName" type="card" id="tabCard" @tab-click="handleClick">
        <el-tab-pane label="单台退库" name="first">
          <div v-if="activeName === 'first'">
            <el-steps :active="disc_current" simple finish-status="success">
              <el-step title="选择移库设备"></el-step>
              <el-step title="选择上级库位"></el-step>
              <el-step title="移库完成"></el-step>
            </el-steps>
            <!-- 第一步分开分配 -->
            <el-row :gutter="20" id="firstCard" v-if="disc_current === 1 && activeName === 'first'">
              <div class="firststorage">
                <el-form :model="forms" @submit.native.prevent>
                  <el-input
                    v-model="forms.imei"
                    @keyup.13.native="enterImei(forms.imei)"
                    placeholder="请通过扫码枪或手动添加获取IMEI号"
                    ref="inputs"
                  ></el-input>
                </el-form>
                <el-button
                  type="primary"
                  slot="append"
                  @click="enterImei(forms.imei)"
                  :loading="isImeiLoading"
                >
                  <span v-if="!isImeiLoading">添加</span>
                  <span v-if="isImeiLoading">添加中</span>
                </el-button>
              </div>
              <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
                <img src="/static/image/device/b-yellow.png" />
              </div>
              <vue-scroll :ops="ops" v-show="!show_one">
                <div style="padding:0px;margin-top: 30px;width: 100%;">
                  <div
                    v-for="(item,index) in searchImei"
                    :key="index"
                    style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                  >
                    <img
                      src="/static/image/device/shebei-1.png"
                      style="float:left;margin:8px 5px 0px 12px;"
                    />
                    {{item.imei}}
                    <img
                      src="/static/image/device/delect_equment.png"
                      style="float:right;margin:16px;"
                      @click="delectImei(item.imei)"
                    />
                  </div>
                </div>
              </vue-scroll>
            </el-row>
            <!-- 第二步 -->
            <el-row
              :gutter="20"
              style="margin-top:30px !important;background:#F8F8F8;"
              v-if="disc_current === 2 &&activeName === 'first'"
            >
              <vue-scroll :ops="ops">
                <div
                  style="width: 100%;display: inline-block;box-sizing: border-box;height:450px;padding:0 27px 30px"
                >
                  <el-col
                    :site="tableSite"
                    :span="4"
                    v-for="(item,index) in tableSite"
                    :key="index"
                    style="width:20%;padding:0"
                  >
                    <div class="grid-content" style="margin: 30px 13px 0px;">
                      <el-button
                        type="info"
                        size="medium"
                        round
                        @click="click_disc_current(index)"
                        :class="disc_active === index ? 'btn-current':''"
                        style="width:156px;border: 1px solid rgba(217,217,217,1);background:#fff;color:#8891A2;white-space: nowrap;text-overflow: ellipsis;overflow:hidden;height: 36px;font-size: 14px;"
                      >{{item.name}}</el-button>
                    </div>
                  </el-col>
                </div>
              </vue-scroll>
            </el-row>
            <div class="dialog-footer footer" v-if="disc_current !== 3 &&activeName === 'first'">
              <el-button
                type="primary"
                class="btnClosed"
                @click="closeDisc"
              >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
              <el-button
                type="primary"
                @click="next"
                :disabled="can_next"
                class="btnSaved"
                :class="{btnAdd:!can_next,add:can_next}"
              >下一步</el-button>
            </div>
            <!-- 第三步 -->
            <el-row
              :gutter="20"
              style="margin:30px 0 0px 0; "
              v-if="disc_current === 3 &&activeName === 'first'"
            >
              <img
                src="/static/image/device/b-red.png"
                alt
                style="margin: 20px auto;display: block;"
              />
              <p style="text-align: center;">已移库完成，3s后将自动关闭弹窗</p>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="整箱退库" name="second">
          <div v-if="activeName === 'second'">
            <el-steps :active="disc_current" simple finish-status="success">
              <el-step title="选择移库设备"></el-step>
              <el-step title="选择上级库位"></el-step>
              <el-step title="移库完成"></el-step>
            </el-steps>
            <!-- 第一步分开分配 -->
            <el-row id="firstCard" v-if="disc_current === 1&&activeName === 'second'">
              <div class="firststorage">
                <el-form :model="set" @submit.native.prevent>
                  <el-input
                    v-model="set.box_number"
                    @keyup.13.native="enterBox(set.box_number)"
                    placeholder="请通过扫码枪或手动添加获取箱号"
                    ref="inputsbox"
                  ></el-input>
                </el-form>
                <el-button
                  type="primary"
                  slot="append"
                  @click="enterBox(set.box_number)"
                  :loading="isBoxLoading"
                >
                  <span v-if="!isBoxLoading">添加</span>
                  <span v-if="isBoxLoading">添加中</span>
                </el-button>
              </div>
              <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
                <img src="/static/image/device/b-yellow.png" />
              </div>
              <vue-scroll :ops="ops" v-show="!show_one">
                <div style="padding:0px;margin-top: 30px;width: 100%;">
                  <div
                    v-for="item in arrbox"
                    :key="item.key"
                    style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                  >
                    <img
                      src="/static/image/device/shebei-1.png"
                      style="float:left;margin:8px 5px 0px 12px;"
                    />
                    {{item}}
                    <img
                      src="/static/image/device/delect_equment.png"
                      style="float:right;margin:16px;"
                      @click="delectBox(item)"
                    />
                  </div>
                </div>
              </vue-scroll>
            </el-row>
            <!-- 第二步 -->
            <el-row
              :gutter="20"
              style="margin-top:30px!important;background:F8F8F8;"
              v-if="disc_current === 2&&activeName === 'second'"
            >
              <vue-scroll :ops="ops">
                <div
                  style="width: 100%;display: inline-block;box-sizing: border-box;height:450px;padding:0 27px 30px"
                >
                  <el-col
                    :site="tableSite"
                    :span="4"
                    v-for="(item,index) in tableSite"
                    :key="index"
                    style="width:20%;padding:0"
                  >
                    <div class="grid-content" style="margin: 30px 13px 0px; ">
                      <el-button
                        type="info"
                        size="medium"
                        round
                        @click="click_disc_current(index)"
                        :class="disc_active === index ? 'btn-current':''"
                        style="width:156px;border: 1px solid rgba(217,217,217,1);background:#fff;color:#8891A2;white-space: nowrap;text-overflow: ellipsis;overflow:hidden;height: 36px;font-size: 14px;"
                      >{{item.name}}</el-button>
                    </div>
                  </el-col>
                </div>
              </vue-scroll>
            </el-row>
            <div class="dialog-footer footer" v-if="disc_current !== 3&&activeName === 'second'">
              <el-button
                type="primary"
                class="btnClosed"
                @click="closeDisc"
              >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
              <el-button
                type="primary"
                @click="next"
                :disabled="can_next"
                class="btnSaved"
                :class="{btnAdd:!can_next,add:can_next}"
              >下一步</el-button>
            </div>
            <!-- 第三步 -->
            <el-row
              :gutter="20"
              style="margin:30px 0 0px 0;"
              v-if="disc_current === 3&&activeName === 'second'"
            >
              <img
                src="/static/image/device/b-red.png"
                alt
                style="margin: 20px auto;display: block;"
              />
              <p style="text-align: center;">已移库完成，3s后将自动关闭弹窗</p>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
  </el-dialog>
</template>
<script>
import Config from "@/config";
import { resolve } from "url";
import { rejects } from "assert";
import qs from "qs";
import { mapGetters } from "vuex";
export default {
  name: "Dispathequment",
  props: ["messagedispath"],
  data() {
    return {
      ops: {
        bar: {
          background: "#DDDEE0"
        }
      },
      // 入库分配弹框
      dialogTablesVisible: false,
      // 选择第二步点击添加颜色
      disc_active: null,
      disc_current: 1,
      //入库分配tab切换
      activeName: "first",
      forms: {
        imei: ""
      },
      set: {
        box_number: ""
      },
      show_one: true,
      searchImei: [], //扫码数据
      arrbox: [], //分配盒子
      saveArr: [],
      // 获取库房站点
      tableSite: [],
      imeiDatas: [],
      boxDatas: [],
      // id: "",
      arr_flag: [],
      checked: false,
      save_flag: "",
      imei_flag: "",
      // 数组去重盒子
      boxArr: [],
      isImeiLoading: false,
      isBoxLoading: false
    };
  },
  methods: {
    // imei搜索
    imei_search() {
      // 搜索imei
      this.isImeiLoading = true;
      var params = {};
      let url = `${Config.DEVICE_MANAGE_URL}/device_house_user/query?devtype=${Config.objType.devtype}`;
      var params = {};
      if (this.district.districtType === 1) {
        params.country = "86";
      } else if (this.district.districtType === 2) {
        params.province = this.district.districtId;
      } else if (this.district.districtType === 3) {
        params.city = this.district.districtId;
      }
      params.imei = this.forms.imei ? this.forms.imei : undefined;
      this.$http
        .get(url, params)
        .then(res => {
          this.isImeiLoading = false;
          if (res.array.length) {
            if (
              res.array[0].dev_equip_id === null ||
              res.array[0].dev_equip_id === ""
            ) {
              // 设置flag 判断库位一致
              if (!this.imei_flag) {
                this.imei_flag = res.array[0].storehouses_name;
              }
              if (this.imei_flag !== res.array[0].storehouses_name) {
                this.$message.error("库位不一致");
                return;
              } else {
                this.searchImei.push(res.array[0]);
                this.show_one = false;
                this.forms.imei = "";
              }
            } else {
              this.$message.error("该设备已被安装");
              this.forms.imei = "";
            }
          } else {
            this.$message("暂无");
            this.forms.imei = "";
          }
        })
        .catch(e => {});
    },
    // 判断有没有imei,imei重复
    search_imei() {
      var a = 0;
      if (!this.searchImei.length) {
        this.imei_search();
      } else {
        this.searchImei.forEach((item, i) => {
          if (item.imei === this.forms.imei) {
            a++;
            this.forms.imei = "";
            this.$message({
              message: "IMEI重复",
              type: "warning"
            });
          }
        });
        if (!a) {
          this.imei_search();
        }
      }
    },
    // 分配扫码监听input框
    enterImei(value) {
      if (value === "") return;
      this.search_imei();
    },
    // 扫码删除
    delectImei(value) {
      this.searchImei.map((item, i) => {
        if (item.imei === value) {
          this.searchImei.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!" });
      if (this.searchImei.length == 0) {
        this.imei_flag = "";
      }
    },
    // box搜索
    box_search() {
      this.isBoxLoading = true;
      var params = {};
      let url = `${Config.DEVICE_MANAGE_URL}/device_house_alldevice_user/query?devtype=${Config.objType.devtype}`;
      var params = {};
      if (this.district.districtType === 1) {
        params.country = "86";
      } else if (this.district.districtType === 2) {
        params.province = this.district.districtId;
      } else if (this.district.districtType === 3) {
        params.city = this.district.districtId;
      }
      params.box_number = this.set.box_number ? this.set.box_number : undefined;
      this.$http
        .get(url, params)
        .then(res => {
          this.isBoxLoading = false;
          this.saveArr = res.array;
          if (!res.array.length) {
            this.$message("暂无");
            return;
          }
          // 判断 dev_equip_id是否一致
          if (res.array.some(res => res.dev_equip_id)) {
            this.$message.error("该箱中有安装设备");
            return;
          }
          var devname = res.array.reduce((bool, response) => {
            return (bool = !bool
              ? bool
              : response.devname === bool
              ? response.devname
              : false);
          }, res.array[0].devname);
          if (!devname) {
            this.$message.error("设备类型不一致");
            return;
          }
          var current_owner = res.array.reduce((bool, response) => {
            return (bool = !bool
              ? bool
              : response.current_owner === bool
              ? response.current_owner
              : false);
          }, res.array[0].current_owner);
          if (!current_owner) {
            this.$message.error("库位不一致");
            return;
          }
          this.arrbox.push(this.set.box_number);
          this.show_one = false;
          this.set.box_number = "";
        })
        .catch(e => {});

      // });
    },
    // 判断有没有箱号  以及重复
    search_box() {
      var a = 0;
      if (!this.arrbox.length) {
        this.box_search();
      } else {
        this.arrbox.map((item, i) => {
          if (item === this.set.box_number) {
            a++;
            this.set.box_number = "";
            this.$message({
              message: "箱号重复",
              type: "warning"
            });
          }
        });
        if (!a) {
          this.box_search();
        }
      }
    },
    // 分配扫码监听input框
    enterBox(value) {
      if (value === "") return;
      this.search_box();
    },
    // 获取库房站点
    getsite(id) {
      let url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_by_id`;
      this.$http
        .get(url, {
          id: id
        })
        .then(res => {
          this.tableSite = [res];
        });
    },
    // 扫码删除
    delectBox(value) {
      this.arrbox.map((item, i) => {
        if (item === value) {
          this.arrbox.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!" });
      if (this.arrbox.length == 0) {
        this.save_flag = "";
      }
    },
    // 入库分配点击切换
    handleClick() {
      this.disc_current = 1;
      this.show_one = true;
      if (this.activeName === "first") {
        this.$nextTick(() => {
          this.$refs.inputs.focus();
        });
        this.show_one = false;
        this.imei_flag = "";
      } else {
        this.$nextTick(() => {
          this.$refs.inputsbox.focus();
        });
        this.save_flag = "";
        this.show_one = false;
      }
    },
    // 颜色切换
    click_disc_current(index) {
      // console.log(index)
      this.disc_active = index;
    },
    //imei分配装箱
    next() {
      // 点击下一步
      if (this.disc_current === 1) {
        this.disc_current = 2;
        this.show_one = false;
        if (this.activeName === "first") {
          if (this.searchImei[0].storehouses_super_id === 1) {
            this.$message.error("当前是最高库位");
            return;
          } else {
            this.getsite(this.searchImei[0].storehouses_super_id);
          }
        } else {
          if (
            this.saveArr.find(res => res.storehouses_super_id)
              .storehouses_super_id === 1
          ) {
            this.$message.error("当前是最高库位");
            return;
          }
          this.getsite(
            this.saveArr.find(res => res.storehouses_super_id)
              .storehouses_super_id
          );
        }
      } else {
        this.$confirm(
          `确定要退库到 ${this.tableSite[this.disc_active].name}?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(value => {
            if (value) {
              // 扫码分配
              if (this.activeName === "first") {
                this.postimei();
              } else {
                // 整箱分配
                this.postbox();
              }
              setTimeout(() => {
                this.dialogTablesVisible = false;
              }, 3000);
            }
            this.$message({
              type: "success",
              message: "退库成功!"
            });
          })
          .catch(() => {
            console.log(123);
            this.$message({
              type: "info",
              message: "已取消退库"
            });
          });
      }
    },
    postimei() {
      // 扫码获取imei
      this.searchImei.map(item => {
        this.imeiDatas.push(item.imei);
      });
      //筛选重复设备类型
      let imei_devname = this.searchImei.map(item => {
        return item.devname;
      });
      let url = `${Config.DEVICE_MANAGE_URL}/inventory/store_house_dispath_by_imei`;
      this.$http
        .post(
          url,
          qs.stringify({
            devtype: Config.objType.devtype,
            imeis: this.imeiDatas.toString(),
            current_owner: this.tableSite[this.disc_active].name,
            current_owner_id: this.tableSite[this.disc_active].id,
            devname: Array.from(new Set(imei_devname)).join(","),
            user_id: this.user.id,
            login_name: this.user.loginName,
            change_info: "dispatch_back"
          }),
          { "Content-Type": "application/x-www-form-urlencoded" }
        )
        .then(res => {
          this.disc_current = 3;
          this.imeiDatas = [];
          this.$emit("change");
        });
    },
    // 整箱分配提交
    postbox() {
      this.arrbox.map(item => {
        this.boxDatas.push(item);
      });
      let url = `${Config.DEVICE_MANAGE_URL}/inventory/store_house_dispath_by_box`;
      this.$http
        .post(
          url,
          qs.stringify({
            devtype: Config.objType.devtype,
            boxs: this.boxDatas.toString(),
            current_owner: this.tableSite[this.disc_active].name,
            current_owner_id: this.tableSite[this.disc_active].id,
            devname: this.saveArr.find(res => res.devname).devname,
            user_id: this.user.id,
            login_name: this.user.loginName,
            change_info: "dispatch_back"
          }),
          { "Content-Type": "application/x-www-form-urlencoded" }
        )
        .then(res => {
          this.disc_current = 3;
          this.boxDatas = [];
          this.$emit("change");
        });
    },
    closeDisc() {
      if (this.disc_current === 1) {
        this.dialogTablesVisible = false;
      } else if (this.disc_current === 2) {
        this.disc_current = 1;
      } else {
        this.dialogTablesVisible = false;
      }
    }
  },
  computed: {
    can_next() {
      if (this.disc_current === 1) {
        if (
          this.arrbox.filter(res => res).length ||
          this.searchImei.filter(res => res.imei).length
        ) {
          if (this.a) {
            return true;
          }
          return false;
        } else {
          return true;
        }
      }
      if (this.disc_current === 2) {
        if (this.disc_active === -1) {
          return true;
        } else {
          return false;
        }
      }
    },
    ...mapGetters("user", {
      district: "getDistrict",
      role: "getRole",
      user: "getUser"
    })
  },
  watch: {
    messagedispath(data) {
      if (data) {
        this.dialogTablesVisible = data;
        this.a = 0;
        // 扫码imei
        this.searchImei = [];
        this.forms.imei = "";
        this.set.box_number = "";
        this.arrbox = [];
        this.disc_active = -1;
        this.show_one = true;
        this.activeName = "first";
        this.dialogTablesVisible = true;
        this.disc_current = 1;
        this.save_flag = "";
        this.imei_flag = "";
        // 自动获取焦点
        this.$nextTick(() => {
          this.$refs.inputs.focus();
        });
        this.boxDatas = [];
        this.imeiDatas = [];
        this.tableSite = [];
      }
    },

    // 弹框关闭
    dialogTablesVisible(data) {
      if (!data) {
        // 子向父
        this.$emit("listendispath", false);
      }
    }
  }
};
</script>